package com.gg.fmallspringboot.service.impl;

import com.gg.fmallspringboot.config.WCPayConfig;
import com.gg.fmallspringboot.entity.*;
import com.gg.fmallspringboot.mapper.OrderMapper;
import com.gg.fmallspringboot.model.Result;
import com.gg.fmallspringboot.service.OrderService;
import com.gg.fmallspringboot.websocket.WebSocketServer;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者:Miki
 * 时间:2021/6/21 12:56
 */
@Transactional
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CarServiceImpl carService;
    @Autowired
    private ProductServiceImpl productService;
    @Autowired
    private ProductSkuServiceImpl productSkuService;
    @Autowired
    private UserAddrServiceImpl userAddrService;
    @Autowired
    private ProductImgServiceImpl productImgService;
    @Autowired
    private OrderItemServiceImpl orderItemService;

    @Override
    public Result saveOrder(String carIds,Integer userId,Integer type,String addrId) {
        //获取提交购物车的详细信息
        List<ShoppingCart> cartList = (List<ShoppingCart>) carService.getOrderCar(carIds, userId).getData();
        String untitled="";
        Double pay=0d;
        for (ShoppingCart cart : cartList) {
            String skuId = cart.getSkuId();
            String productId = cart.getProductId();
            //更具购物车里面的skuid 来获取改购物车物品对应的库存
            ProductSku productSku = productSkuService.getOne(skuId);
            Integer stock = productSku.getStock();
            if (stock<Integer.parseInt(cart.getCartNum())){
                return new Result(1,"库存不足，订单创建失败");
            }
            //库存充足，计算总价钱
            pay+=productSku.getSellPrice()*Integer.parseInt(cart.getCartNum());
            untitled=untitled+productService.getOne(productId).getProductName()+",";
        }
        UserAddr userAddr = userAddrService.getOne(addrId).getData();
        String orderId = UUID.randomUUID().toString().replace("-", "");
        //创建一个订单对象，将添加订单所需要的信息存放进去
        Orders order = new Orders();
        order.setOrderId(orderId);
        order.setUserId(userId+"");
        order.setUntitled(untitled);
        order.setActualAmount(pay.intValue());
        order.setTotalAmount(new BigDecimal(pay));
        order.setUserAddr(userAddr);
        order.setPayType(type);
        order.setStatus(1+"");
        order.setCreateTime(new Date());
        int count = orderMapper.saveOrder(order);
        if (count==1){
            //订单生成成功，删除购物车里面的数据
            carService.deleteCar(carIds);
            //添加订单详情
            for (ShoppingCart cart : cartList) {
                ProductSku productSku = productSkuService.getOne(cart.getSkuId());
                String skuName = productSku.getSkuName();
                BigDecimal totalAmount= new BigDecimal(productSku.getSellPrice()*Integer.parseInt(cart.getCartNum()));
                String productName = productService.getOne(cart.getProductId()).getProductName();
                String productImg = productImgService.getOneByProId(cart.getProductId()).getUrl();
                String oiId=UUID.randomUUID().toString().replace("-","");
                OrderItem oi = new OrderItem(oiId,order.getOrderId(),cart.getProductId(),productName,productImg,cart.getSkuId(),skuName,cart.getProductPrice(),Integer.parseInt(cart.getCartNum()),totalAmount,cart.getCartTime(),new Date(),0);
                orderItemService.add(oi);
            }

        }
        return new Result(0,"添加订单成功",order);
    }

    @Override
    public String updateOrder(HttpServletRequest request) {
        InputStream inStream=null;
        try{
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inStream.read(buffer)) != -1){
                outSteam.write(buffer,0,len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(),"utf-8");

            //对xml进行解析 map
            Map<String,String> map = WXPayUtil.xmlToMap(result);
            //验证签名,判断是不是微信支付端发过来的请求
            boolean signatureValid = WXPayUtil.isSignatureValid(map,
                    new WCPayConfig().getKey());

            if(signatureValid&&"SUCCESS".equals(map.get("result_code"))){
                //修改订单状态(支付状态、订单状态、支付时间、修改时间)
                Orders order = new Orders();
                order.setStatus(4+"");
                order.setOrderId(map.get("out_trade_no"));
                int count = orderMapper.update(order);
                //返回给前端支付成功的信息
                WebSocketServer.sendMsg(map.get("out_trade_no"),"1");

                if (count==1) {
                    System.out.println("订单状态修改成功");
                    //给微信返回处理后的信息
                    Map<String,String> resp = new HashMap<>();
                    resp.put("return_code","SUCCESS");
                    resp.put("return_msg","OK");
                    String s = WXPayUtil.mapToXml(resp);
                    return s;
                }
            }

        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
        return null;
    }

    @Override
    public Orders getOrderById(String orderId) {

        return orderMapper.selectOne(orderId);
    }
}
